package chain;


import java.util.ArrayList;
import java.util.List;

class Msg{
    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    private String msg;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private String name;

    @Override
    public String toString() {
        return "Msg{" +
                "msg='" + msg + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}

/**
 * 过滤器
 */
@FunctionalInterface
interface Filter{
    boolean doFilter(Msg msg);
}

/**
 * HtML过滤器
 */
class HtmlFilter implements Filter{

    @Override
    public boolean doFilter(Msg msg) {
        String ms = msg.getMsg();
        ms = ms.replace('<','[');
        ms = ms.replace('>',']');
        msg.setMsg(ms);
        return true;
    }
}

/**
 * 时间过滤器
 */
class TimeFilter implements Filter{

    @Override
    public boolean doFilter(Msg msg) {
        String ms = msg.getMsg();
        ms = ms.replaceAll("996","955");
        msg.setMsg(ms);
        return false;
    }
}

/**
 * 链式处理过滤器
 */
class ChainOfRes implements Filter{
    private List<Filter> chainList = new ArrayList<>();

    @Override
    public boolean doFilter(Msg msg) {
        for (Filter filter: chainList){
            if(!filter.doFilter(msg)){
                return false;
            }
        }
        return true;
    }

    // 注册过滤器
    public ChainOfRes register(Filter filter){
        chainList.add(filter);
        return this;
    }
}

/**
 * 责任链设计模式
 */
public class Chain {
    public static void main(String[] args) {
        Msg msg = new Msg();
        msg.setMsg("<script>996</script>");

        // 注册过滤器
        HtmlFilter htmlFilter = new HtmlFilter();
        TimeFilter timeFilter = new TimeFilter();

        // 链条组1
        ChainOfRes chainOfRes = new ChainOfRes();
        chainOfRes.register(htmlFilter);
        // 链条组2
        ChainOfRes chainOfRes2 = new ChainOfRes();
        chainOfRes2.register(timeFilter);
        chainOfRes2.register((msg1)->{
           String ms = msg1.getMsg();
           ms = ms.replace('s','q');
           msg1.setMsg(ms);
           return true;
        });
        // 拼装两组链条 - 这就是为什么Chain 去在实现 Filter可以把组也穿到一起。
        chainOfRes.register(chainOfRes2);
        // 执行
        chainOfRes.doFilter(msg);

        System.out.println(msg.getMsg());
    }
}
